<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    /*
        1.提前终止迭代器
            可选的 return()方法用于指定在迭代器提前关闭时执行的逻辑
            可以"关闭"迭代器的方法:
                for-of 循环通过break continue return throw
                解构操作并未消费所有值(就是只解构了几个值,没有全部解构)
     */

    class Counter {
        constructor(limit) {
            this.limit = limit
        }

        [Symbol.iterator]() {
            let count = 1,
                limit = this.limit;
            return {
                next() {
                    if (count <= limit) {
                        return {done: false, value: count++}
                    } else {
                        return {done: true}
                    }
                },
                return() {
                    console.log('Exiting early')
                    return {done: true}
                }
            }
        }
    }

    // 1.1 break
    let counter = new Counter(5);
    for (let i of counter) {
        if (i > 2) {
            break;
        }
        console.log(i)  // 1 2 Exiting early
    }

    // 1.2 throw
    let counter2 = new Counter(5)
    try {
        for (let i of counter2) {
            if (i > 2) {
                throw 'err'
            }
            console.log(i)  // 1 2  Exiting early
        }
    } catch (e) {
    }
    
    // 1.3 解构
    let counter3 = new Counter(5)
    let [c,b] = counter3;       // Exiting early
    console.log(c,b)  // 1 2 
    
    /*
        2.如果迭代器没有关闭,还可以继续从上次离开的地方继续迭代
            因为return()方法是可选的,所以并非所有迭代器都可以关闭
     */
    let a = [1,2,3,4,5]
    let iter = a[Symbol.iterator]();
    for(let i of iter){
        console.log(i)  // 1 2 3 
        if(i>2){
            break;
        }
    }
    for(let i of iter){
        console.log(i)  // 4 5
    }
    
    

</script>
</body>
</html>